'''
Description: 
Author: Zilu
Date: 2021-11-18 20:55:18
Version: 
LastEditTime: 2021-11-19 00:26:48
LastEditors: Zilu
'''

# asyncio可以实现单线程并发IO操作
# asyncio实现了TCP、UDP、SSL等协议，aiohttp则是基于asyncio实现的HTTP框架 
import asyncio
from asyncio.events import AbstractEventLoop
from aiohttp import web

async def index(request):
    await asyncio.sleep(0.5)
    # 需要指定响应头地内容类型是 html，不然就是 plain
    return web.Response(body=b'<h1>Index</h1>', content_type='text/html')

async def hello(request):
    await asyncio.sleep(0.5)
    text = '<h1>Hello, %s</h1>' % request.match_info['name']
    return web.Response(body=text.encode('utf-8'), content_type='text/html')

async def init(loop:AbstractEventLoop):
    app = web.Application(loop=loop)
    app.router.add_route('GET', '/', index)
    app.router.add_route('GET', '/hello/{name}', hello)
    srv = await loop.create_server(app.make_handler(), '127.0.0.1', 8000)
    print('Server started at http://127.0.0.1:8000')
    return srv

loop = asyncio.get_event_loop()
loop.run_until_complete(init(loop))
loop.run_forever()

# 注意aiohttp的初始化函数init()也是一个coroutine，loop.create_server()则利用asyncio创建TCP服务


